<?php

/**
 * @file
 *  This file contains the form generation function
 */
require_once(SHMS_CORE_PATH."/shms_core_form_person.inc");
require_once(SHMS_CORE_PATH."/shms_db_person.inc");

function shms_person_form_add($form,&$form_state){
  $form = shms_core_person_form_basic();
  
  shms_core_person_form_add_room_number_field_for_basic($form,2);
  shms_core_form_add_submit_button_for_basic($form,21,t("submit"));
  
  return $form;
}

function _shms_person_individual_form_validate_duplicate_matric_no_and_change_case_to_upper($form,&$form_state){
  $values = &$form_state['values'];
  $pdata = shms_core_db_load_from_table(SHMS_PERSON_TABLE,'matric_no', $values['matric_no']);
  if(!empty($pdata)){
    form_set_error('matric_no',"Duplicated matric number encountered. matric number: ".$values['matric_no']);
  } else{
    $values['matric_no'] = strtoupper($values['matric_no']);  // change to upper case
  }
}

function _shms_person_individual_form_validate_format($form,&$form_state){
  $values = &$form_state['values'];
  if(!shms_core_person_matric_number_is_correct_format($values['matric_no'])){
    form_set_error('matric_no',"Please put in correct format of the matric number.");
  } 
  
  if(!shms_core_person_email_address_is_correct_format($values['personal_email'])){
    form_set_error('personal_email',"Please put in correct format of personal email address.");
  }
  $nus_email = trim($values['nus_email']); $nus_email_endding = "nus.edu.sg";
  if( 
    !shms_core_person_email_address_is_correct_format($nus_email) || 
    substr_compare($nus_email, $nus_email_endding, -strlen($nus_email_endding), strlen($nus_email_endding)) != 0){
    form_set_error('nus_email',"Please put in correct format of the nus email address.");
  }
  
  if(!shms_core_room_number_is_correct_format($values['room_number'])){
    form_set_error('room_number',"Please strictly follows the room_number format.");
  }
}

function _shms_person_individual_form_validate_and_transform_dob($form, &$form_state){
  $dob = &$form_state['values']['date_of_birth'];
  $dob = mktime(0,0,0,$dob['month'],$dob['day'],$dob['year']);
}

function shms_person_form_add_validate($form,&$form_state){
  _shms_person_individual_form_validate_format($form, $form_state);
  _shms_person_individual_form_validate_duplicate_matric_no_and_change_case_to_upper($form,$form_state);
}

function shms_person_form_add_submit($form,&$form_state){
  $values = &$form_state['values'];
  $values['personal_detail_filled'] = TRUE;
  if( shms_core_db_add_person($values)){
    drupal_set_message("Add person succeed!");
  } else{
    drupal_set_message("Add person failed!","error");
  }
}

function shms_person_form_list($form,&$form_state,$blk = 'all'){
  $blk_arr = shms_core_common_get_block_list() + array('all' => "All");
  
  // link to the corresponding block
  $form['link_group'] = array();
  foreach($blk_arr as $leter => $name){
    $form['link_group'][] = array(
      '#markup' => $blk == $leter ? "<span class = 'blk_link'>".$name."</span>": 
        l($name,SHMS_PERSON_PATH."/list/".$leter,array('attributes' => array('class' => array('blk_link')))),
    );
  }
  drupal_add_css(SHMS_COMMON_CSS_PATH,'file');
  
  // get person list
  $residents = shms_core_db_load_persons_by_blk($blk);
  
  // and create table for the form
  $header = array('Full Name','Matric No.','Room Number','Email Address','Option');
  $rows = array();
  foreach($residents as $id => $info){
    $rows[] = array(
      $info['full_name'],$info['matric_no'], $info['room_number'],$info['personal_email'],
      user_access(SHMSP_PRESIDENT)?l('Edit',SHMS_PERSON_PATH."/".$id."/edit"):"",
    );
  }
  $form['list'] = array("#markup" => theme("table",array('header'=>$header,'rows'=>$rows)));
  
  return $form;
}

function shms_person_form_edit($form,&$form_state,$person_id = NULL){
  if(empty($person_id)){
    // if non-exist then assign an person ID and load 
    global $user;
    $person_info = shms_core_db_load_from_table(SHMS_PERSON_TABLE, 'duid',$user->uid);
    $person_id = $person_info['id'];
  } 
  
  if(!empty($person_id)){
    $person_all_info = shms_core_db_load_all_data_for_person($person_id);
  }
  if(empty($person_all_info) || empty($person_id)){
    drupal_set_message("Person with id '".$person_id."' doesn't exist.","error");
    return array();
  }
  
  // check user permission first
  global $user;
  if(!shms_user_with_super_access() && !($person_all_info['basic']['duid'] == $user->uid)){
    drupal_set_message("Sorry you don't have permission to this page.","error");
    return array();
  }
  
  $person_all_info['basic']['date_of_birth'] = shms_core_get_date_arr_from_timestamp($person_all_info['basic']['date_of_birth']);
  
  // build form
  global $user;
  $form['info'] = array('#markup'=>t("Plase ".l("click here","user/".$user->uid."/edit")." for changing the password"));
  $form += shms_core_person_form_basic($form,$form_state); 
  shms_core_person_form_add_room_number_field_for_basic($form, 2);
  shms_core_form_add_submit_button_for_basic($form, 21, "Update");
  $form['id'] = array('#type' => 'value', '#value' => $person_id);
  $form['matric_no']['#disabled'] = TRUE;$form['room_number']['#disabled'] = TRUE;
  
  // add default value info
  $person_default_value = $person_all_info['basic'] + array_shift($person_all_info['by_year']);
  shms_add_default_value_for_fields($form, $person_default_value);
  return $form;
}


function shms_person_form_edit_validate($form,&$form_state){
  _shms_person_individual_form_validate_format($form, $form_state);
  _shms_person_individual_form_validate_and_transform_dob($form, $form_state);
  
  // and check if value has been changed or not, and user do have the edit right to this person
  $values = $form_state['values'];
  $old_person_info = shms_core_db_load_all_data_for_person($values['id']);
  $newest_person_year_data = array_shift($old_person_info['by_year']);
  if(
          empty($old_person_info)                                            
      ||  !shms_core_user_has_edit_right_to_person($old_person_info['basic']['duid'])
      ||  $old_person_info['basic']['matric_no'] != $values['matric_no']
      ||  $newest_person_year_data['room_number'] != $values['room_number']
  ){
    form_set_error('matric_no',"Cannot update because not allowed information has been changed.");
    form_set_error('room_number',"Please Do Not Try to Hack the System.");
  }
}


function shms_person_form_edit_submit($form,&$form_state){
  $values = &$form_state['values'];
  $values['personal_detail_filled'] = TRUE;
  
  $personArrStruc = shms_core_db_get_person_array_struc();
  unset($personArrStruc['duid']);
  $personUpdateInfo = shms_sort_array_data_into_subarr($values,array('person' => $personArrStruc));
  
  if( shms_core_db_update_person($personUpdateInfo['person'])){
    drupal_set_message("Update Succeed!");
  } else{
    drupal_set_message("Update Failed!","error");
  }
}

function shms_person_name_auto_complete_matrix_keyed($str = ""){
  $query = db_select(SHMS_PERSON_TABLE,'p');
  $query->innerJoin(SHMS_PERSON_BY_YEAR_TABLE,'py',"p.id = py.pid");
  $query->fields('p',array('matric_no','full_name'));
  $query->fields('py',array('room_number'));
  $query->condition('py.year',shms_get_current_academic_year());
  $condition = db_or()->condition('p.full_name',"%".$str."%","LIKE")
                      ->condition('p.matric_no',"%".$str."%","LIKE")
                      ->condition('py.room_number',"%".$str."%","LIKE");
  $query->condition($condition);
  $query->orderBy('p.full_name',"ASC");
  $query->range(0,variable_get(SHMS_PERSON_AUTO_COMPLETE_SIZE_TERM,15));
  $result = $query->execute();

  $matches = array();
  while($record = $result->fetchAssoc()){
    $outputstr = $record['full_name']." - ".$record['room_number']." - ".$record['matric_no'];
    $dataStr = $record['full_name']." - ".$record['matric_no'];
    $matches[$outputstr] = $outputstr;
  }
  drupal_json_output($matches);
}

function shms_person_batch_add_form_get_min_required_fields(){
  return array(
    'full_name' => t("Full Name"),
    'matric_no' => t("Matric No"),
    'gender'    => t("Gender"),
  );
}

function shms_person_batch_add_form($form = array(),&$form_state){
  $desc_string = "donwload the template form  ".l("here",SHMS_CORE_PATH."/files/batch_person_template.csv");
  $form['info'] = array('#markup'=>$desc_string);
  $form['file'] = array(
    '#type' => "managed_file",
    '#title'=> t("CSV File"),
    '#required'   => TRUE,
    '#upload_location'    => "public://tmp/person_list",
    '#progress_indicator' => "bar",
    "#upload_validators"  => array("file_validate_extensions" => array("csv")),
    '#weight' => 3,
  );
  $form['submit']  = array(
    '#type' => "submit",
    '#value'=> t("Submit"),
    "#weight" => 20,
  );
  return $form;
}

/**
 * Do the validation, check:
 */
function shms_person_batch_add_form_validate($form,&$form_state){
  // read the csv file
  $file = file_load($form_state['values']['file']);
  
  // if it's the csv file, can just use PHP's csv library
  $fp = fopen(drupal_realpath($file->uri),"r");
  $standard_error_string = "Person Parse Error: cannot recognize :type for person ".
                      ":name submitted value: :value, on line :line_no\n";
  
  // parse file
  $first_line = fgetcsv($fp); // ignore the first line
  if(sizeof($first_line) > 5){
    drupal_set_message("Sorry cannot recognize the default excel file. Please ".
    "contact Song Yangyu(HP: 81030389, Email: flyfy1@gmail.com) to help you with this.","error");
  }
  drupal_set_message("<pre>".print_r($first_line,TRUE)."</pre>","error");
  $error_message = ""; $person_arr = array();
  for($line_no = 1; $person = fgetcsv($fp); $line_no++){
    // properly set the variable for the person field
    // 0 - Full Name, 1 - Matric No, 2 - Gender
    $person['personal_detail_filled'] = 0;
    $person['full_name']  = $person[0];
    $person['matric_no']  = strtoupper(trim($person[1]));
    $person['gender']     = strtoupper(trim($person[2]));
    $person['room_number']= strtoupper(trim($person[3]));
    
    // validate gender format
    if(!preg_match("/^[FM]$/", $person['gender'])){
      $error_message.= str_replace(array(':type',':name',':value',':line_no'), 
                                    array('gender', $person['full_name'],
                                          $person['gender'],$line_no),
                                    $standard_error_string);
    } else{ // and translate accordingly
      $person['gender'] = ($person['gender'] == 'M'?SHMS_GENDER_MALE:SHMS_GENDER_FEMALE);
    }
    // validate Matric No format
    if(!shms_core_person_matric_number_is_correct_format($person['matric_no'])){
      $error_message .= str_replace(array(':type',':name',':value',':line_no'), 
                                    array('matric number', $person['full_name'],
                                          $person['matric_no'],$line_no),
                                    $standard_error_string);;
    }
    // validate room number format
    if(!shms_core_room_number_is_correct_format($person['room_number'])){
      $error_message .= str_replace(array(':type',':name',':value',':line_no'), 
                                    array('room number', $person['full_name'],
                                          $person['room_number'],$line_no),
                                    $standard_error_string);;
    }
    // set the person individual info properly
    $person_arr[] = $person;
  }
  if($error_message != "") form_set_error("file",$error_message);
  else{
    $form_state['storage']['parr'] = $person_arr;
  }
}

function shms_person_batch_add_form_submit($form,&$form_state){
  
  $ts = db_transaction(); $success_str = "";
  try{
    foreach($form_state['storage']['parr'] as $person){
      // check if person duplicate 
      $pdata = shms_core_db_load_from_table(SHMS_PERSON_TABLE,'matric_no', $person['matric_no']);
      
      if(empty($pdata)){  // when person is not a previous user, add in directly
        if(shms_core_db_add_person($person)){
          $success_str .= "Person added successfully, name: ".$person['full_name']."</br>";
        } else{
          throw new Exception("Error in adding person ".$person['full_name']);
        }
      } else{ // otherwise
        $pydata = db_select(SHMS_PERSON_BY_YEAR_TABLE,'t')->fields('t')
               ->condition("pid",$pdata['id'])
               ->condition('year',shms_get_current_academic_year())->execute()->fetchAssoc();
        if(empty($pydata)){
        // on no current-year record, add the current year record;
          $py = array(
            'pid'  => $person['id'],
            'room_number'   => $person['room_number'],
            'year' => shms_get_current_academic_year(),
            'sem'  => 0,  // assume full year
          );
          if(drupal_write_record(SHMS_PERSON_BY_YEAR_TABLE, $py) != SAVED_NEW){
            throw new Exception("Error in generating current year record for person: ".$person['full_name']);
          } else{
            $success_str .= "New current year record generated successfully for person: ".$person['full_name']."</br>";
          }
        } else{
          // on having current-year record, update it
          $py = array(
            'id'    => $pydata['id'],
            'pid'   => $pydata['pid'],
            'room_number'   => $person['room_number'],
            'year' => shms_get_current_academic_year(),
          );
          if(drupal_write_record(SHMS_PERSON_BY_YEAR_TABLE, $py,"id") != SAVED_UPDATED){
            throw new Exception("Error in updating current year record for person: ".$person['full_name']);
          } else{
            $success_str .= "Current Year record has been updated successfully for person: ".$person['full_name']."</br>";
          }
        }
      }
    }
    drupal_set_message($success_str."\n".
        "The list of person in the form has been added successfully.".
        " They can use their matric number as username and password ".
        " to login, and they can change their password once after ".
        "logging in. The matric number is capitalized.");
  }catch(exception $e){
    $ts->rollback();
    drupal_set_message("Sorry error occured while updating the record, error message: ".$e->__toString(),"error");
  }
}

function shms_person_form_inv($form,&$form_state){
  // list info about oneself
  return $form;
}
